package com.event.listener;

import com.event.util.EventHandler;
import com.event.util.EventType;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 事件处理器的监听器
 */
@Component
@ConditionalOnBean(EventHandler.class)
@SuppressWarnings("ALL")
public class EventHandlerListener {

    @Autowired
    private List<EventHandler> eventHandlers;

    /**
     * 读取消费端的确认模式
     */
    @Value("${spring.rabbitmq.listener.simple.acknowledge-mode}")
    private String ackMode;

    /**
     * 设置消费者监听的队列
     */
    @RabbitListener(queues = "event_queue_${spring.application.name}")
    public void msgHandler(Message message, Channel channel){
        //获得消息内容
        byte[] body = message.getBody();
        //反序列化消息对象
        Object msg = SerializationUtils.deserialize(body);

        //获取路由键
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();

        //依次匹配消费端的EventHandler实现类
        eventHandlers.forEach(eventHandler -> {
            //获得EventHandler实现类的注解
            EventType eventType = eventHandler.getClass().getAnnotation(EventType.class);
            if (routingKey.equals(eventType.value())) {

                try {
                    //当前路由键 匹配上了 当前的实现类，该事件应该交给当前的实现类处理
                    eventHandler.msgHandler(msg);
                    //手动确认
                    if (ackMode.equals("manual")) {
                        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

                return;
            }
        });
    }
}
